const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const formatDateTime = require('../utils/formatDateTime');
const notificationService = require('../services/notification.service');

// 获取用户通知列表
exports.getNotificationByUserId = async (req, res) => {
  try {
    const userId = parseInt(req.query.userId);

    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '请提供用户ID'
      });
    }

    // 获取用户的所有通知
    const notifications = await prisma.system_notification.findMany({
      where: {
        recipient_id: userId
      },
      orderBy: {
        create_time: 'desc'
      },
      include: {
        // 这里无法直接关联，因为数据库模型中没有定义关系
        // 所以我们需要手动处理
      }
    });

    // 获取通知总数
    const total = notifications.length;

    // 获取未读通知数量
    const unreadTotal = notifications.filter(notification => notification.is_read === 0).length;

    // 获取所有发送者的ID（排除null值）
    const senderIds = notifications
      .map(notification => notification.sender_id)
      .filter(id => id !== null);

    // 获取所有发送者的信息
    const senders = await prisma.user.findMany({
      where: {
        id: {
          in: senderIds
        }
      },
      select: {
        id: true,
        name: true
      }
    });

    // 创建发送者ID到名称的映射
    const senderMap = {};
    senders.forEach(sender => {
      senderMap[sender.id] = sender.name;
    });

    // 获取所有通知类型
    const notificationTypes = await prisma.notification_type.findMany();
    
    // 创建通知类型ID到名称的映射
    const notificationTypeMap = {};
    notificationTypes.forEach(type => {
      notificationTypeMap[type.id] = type.name;
    });

  
    // 格式化通知列表
    const list = notifications.map(notification => ({
      notificationId: notification.id,
      senderId: notification.sender_id,
      senderName: notification.sender_id ? senderMap[notification.sender_id] || '未知用户' : '系统',
      notificationType: notificationTypeMap[notification.notification_type_id] || '未知类型',
      content: notification.content,
      createTime: formatDateTime(notification.create_time),
      isRead: notification.is_read
    }));
    

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        list,
        total,
        unreadTotal
      }
    });
  } catch (error) {
    console.error('获取通知列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取通知列表失败'
    });
  }
};

// 更新通知为已读状态
exports.updateNotificationRead = async (req, res) => {
  try {
    const notificationId = parseInt(req.query.notificationId);

    if (!notificationId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '请提供通知ID'
      });
    }

    // 查询通知是否存在
    const notification = await prisma.system_notification.findUnique({
      where: {
        id: notificationId
      }
    });

    if (!notification) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '通知不存在'
      });
    }

    // 如果通知已经是已读状态，则直接返回成功
    if (notification.is_read === 1) {
      return res.status(200).json({
        code: 200,
        message: 'success',
        data: null
      });
    }

    // 更新通知状态为已读，并记录阅读时间
    await prisma.system_notification.update({
      where: {
        id: notificationId
      },
      data: {
        is_read: 1,
        read_time: new Date()
      }
    });

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: null
    });
  } catch (error) {
    console.error('更新通知状态失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '更新通知状态失败'
    });
  }
};
